<?php

function render($code, $message, $result = '') {
//    if ($result && !is_object($result)) {
//        $result = array_merge($result, array('site_url' => C('SITE_URL'),));
//        echo json_encode(array(
//            'code' => $code,
//            'message' => $message,
//            'result' => $result
//        ));
//    }else{
//        echo json_encode(array(
//            'code' => $code,
//            'message' => $message,
//        ));
//    }

    if ($code == '10000') {
        if ($result && !is_object($result)) {
            $result = array_merge($result, array('site_url' => C('SITE_URL')));
        }
        echo json_encode(array(
            'code' => $code,
            'message' => $message,
            'result' => $result
        ));
    }else{
        echo json_encode(array(
            'code' => $code,
            'message' => $message,
        ));
    }
//    lichen 2019/5/30 start
//    $result = set_null($result);
//    lichen 2019/5/30 end

    exit;
}

function set_null($data) {
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            $data[$key] = set_null($val);
        }
    }
    if ((is_string($data) && $data === '') || (is_array($data) && $data === array())) {
        $data = NULL;
    }
    return $data;
}


/**
 *    获取订单状态相应的文字表述
 */
function order_status($order_status) {
    $lang_key = '订单状态错误';
    switch ($order_status) {
        case ORDER_PENDING:
            $lang_key = '待付款';
            break;
        case ORDER_SUBMITTED:
            $lang_key = '已提交';
            break;
        case ORDER_ACCEPTED:
            $lang_key = '待发货';
            break;
        case ORDER_SHIPPED:
            $lang_key = '已发货';
            break;
        case ORDER_FINISHED:
            $lang_key = '已完成';
            break;
        case ORDER_CANCELED:
            $lang_key = '已取消';
            break;
    }
    return $lang_key;
}

/**
 *    获取物流状态相应的文字表述
 */
function express_status($status) {
    switch ($status) {
        case 0:
            $lang_key = '在途';
            break;
        case 1:
            $lang_key = '揽收';
            break;
        case 2:
            $lang_key = '疑难';
            break;
        case 3:
            $lang_key = '签收';
            break;
        case 4:
            $lang_key = '退签';
            break;
        case 5:
            $lang_key = '派件';
            break;
        case 6:
            $lang_key = '退回';
            break;
    }
    return $lang_key;
}

/**
 * 发送get请求
 * @param string $url
 * @return bool|mixed
 */
function request_get($url = '') {
    if (empty($url)) {
        return false;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    //curl_redir_exec($ch);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Errno' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

/**
 * 发送post请求
 * @param string $url
 * @param string $param
 * @return bool|mixed
 */
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Errno' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

function real_ip() {
    static $realip = NULL;

    if ($realip !== NULL) {
        return $realip;
    }

    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip) {
                $ip = trim($ip);

                if ($ip != 'unknown') {
                    $realip = $ip;

                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            } else {
                $realip = '0.0.0.0';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}
function set_encrypt($data, $key = 'asa')
{
    $data = (string)$data;
    $key    =    md5($key);
    $x        =    0;
    $len    =    strlen($data);
    $l        =    strlen($key);
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}
function get_decrypt($data, $key = 'asa')
{
    $key = md5($key);
    $x = 0;
    $data = str_replace(' ','+',$data);
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
        {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }
        else
        {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}

function sync_data($url, $data_string) {
    $data_string = json_encode($data_string);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    $res = curl_exec($ch);
    if(!$res){
        return $res;
    }else{
        return json_decode($res,true);
    }
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $return_content = ob_get_contents();
    ob_end_clean();

    return array('code'=>$return_code, 'result'=>$return_content);
}

function set_redis($key,$keyword){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    //zScore 查看分数
    if(!$redis ->zScore($key,$keyword)){
        $redis -> zAdd($key,1,$keyword);
    }else{
        $count = $redis ->zScore($key,$keyword) + 1;
        $redis -> zAdd($key,$count,$keyword);
    }
}

////日活
function set_day_login_redis($user_id){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    $time = strtotime(date('Y-m-d',time()));
    $redis->setBit('memberlogin_'.$time, $user_id, 1);
}

//浏览量
function set_day_statistics_redis($key){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    //当前时间0点0分0秒
    $time = strtotime(date('Y-m-d',time()));
    $redis->hIncrBy($key, $time, 1);
}

function get_day_statistics_redis($key,$time){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    //当前时间0点0分0秒
//    $time = strtotime(date('Y-m-d',time()));
    return $redis->hGet($key, $time);
}

//一键登录验证
function set_oneclick_redis($key,$user_id,$keyword){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->hDel($key, 'asa0'.$user_id);
    $redis->hSet($key,'asa0'.$user_id,$keyword);
}

function get_oneclick_redis($key,$user_id){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    return $redis->hGet($key,'asa0'.$user_id);
}

function test_hash(){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->hDel('asd', 'asa03');
    $redis->hSet('asd','asa03',md5('asa03'.time()));
    var_dump($redis->hGet('asd','asa03'));
}

//二维数组排序
function arraySort($arr,$key,$type='asc'){
    $keyArr = array(); // 初始化存放数组将要排序的字段值
    foreach ($arr as $k=>$v){
        $keyArr[$k] = $v[$key]; // 循环获取到将要排序的字段值
    }
    if($type == 'asc'){
        asort($keyArr); // 排序方式,将一维数组进行相应排序
    }else{
        arsort($keyArr);
    }
    $newArray = array();
    foreach ($keyArr as $k=>$v){
        $newArray[$k] = $arr[$k]; // 循环将配置的值放入响应的下标下
    }
    $newArray = array_merge($newArray); // 重置下标


    $arrArray['first'] = '';
    $arrArray['end'] = '';
    $num = count($newArray) - 1;
    $count = 0;
    foreach($newArray as $key =>$value){
        if($value['price'] == 0.00){
            $count ++;
            continue;
        }else{
            $arrArray['first'] = $newArray[$count]['price'];
            $arrArray['end'] = $newArray[$num]['price'];
            break;
        }
    }
    return $arrArray;
}

////二维数组排序(new)
function array_sort($arr,$key,$type='asc'){
    $keyArr = array(); // 初始化存放数组将要排序的字段值
    foreach ($arr as $k=>$v){
        $keyArr[$k] = $v[$key]; // 循环获取到将要排序的字段值
    }
    if($type == 'asc'){
        asort($keyArr); // 排序方式,将一维数组进行相应排序
    }else{
        arsort($keyArr);
    }
    $newArray = array();
    foreach ($keyArr as $k=>$v){
        $newArray[$k] = $arr[$k]; // 循环将配置的值放入响应的下标下
    }
    $newArray = array_merge($newArray); // 重置下标

    $arrArray['first'] = '';
    $arrArray['end'] = '';
    $num = count($newArray) - 1;
    $count = 0;
    foreach($newArray as $k1 =>$v1){
        if($v1[$key] == 0.00){
            $count ++;
            continue;
        }else{
            $arrArray['first'] = $newArray[$count][$key];
            $arrArray['end'] = $newArray[$num][$key];
            break;
        }
    }
    return $arrArray;
}

function connectRedis(){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    return $redis;
}

function _curl_to_oms($url,$data){
    $data_string = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    $res = curl_exec($ch);
    if($url == 'http://api.jingjing.shop/api/order/UpdateOrderStatus'){
        var_dump($res);exit;
    }
    if(!$res['MessageCode']){
        render('10004', '同步失败');
    }else{
        $rs = json_decode($res,true);
        if($rs['MessageCode'] == 2){
            render('10004', $rs['ErrorMsg']);
        }else if($rs['MessageCode'] == 1){
//            return json_decode($res,true);
        }else{
            render('10004', '连接超时');
        }
    }
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $return_content = ob_get_contents();
    ob_end_clean();

    return array('code'=>$return_code, 'result'=>$return_content);
}

function get_discount($token,$goods_id){
    $res_member = M('app_token')->join('left join ecm_member on ecm_app_token.user_id = ecm_member.user_id')->where(array('token'=>$token))->find();
    if(!$res_member){
        return false;
    }
    $res_region = M('region')->where(array('region_id'=>$res_member['s_id']))->find();
    if(!$res_region){
        return false;
    }
    $cond['store_id'] = array('IN',$res_region['region_id'].','.$res_region['parent_id']);
    $res_store = M('store')->where($cond)->find();
    if(!$res_store){
        return false;
    }
    $conds['goods_id'] = $goods_id;
    $conds['stock_style'] = 3;
    $conds['stock'] = array('egt',0);
    $conds['price'] = array('egt',0);
    $res_goods = M('goods_spec')->join('left join ecm_storestock on ecm_goods_spec.spec_3value = ecm_storestock.storestock_id')->where($conds)->find();
    if(!$res_goods){
        return false;
    }
    return true;



}

function get_wish_log_price($wish_id,$template_id){
    //判断是否为老心愿单
    $res_old = M('wish_log')->where(array('wish_id'=>$wish_id,'stage'=>0))->find();
    $res_old_money = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where(array('wish_id'=>$wish_id))->find();
    $res_wish = M('wish')->where(array('id'=>$wish_id))->find();
    $res_pay1 = M('wish_pay_log')->where(array('wish_id'=>$wish_id,'type'=>1))->find();
    if($res_old){
        if($res_old_money['smoney'] + $res_pay1['money'] >= $res_wish['goods_price']){
            return false;
        }
        return array(
            'money' => '30',
            'sign' => '',
            'stage' => '0',
            'fsh' => $res_old_money['smoney'] + 30 + $res_pay1['money']>= $res_wish['goods_price'] ? true : false
        );
    }
    if($res_old_money['smoney'] + $res_pay1['money'] >= $res_wish['goods_price']){
        return false;
    }
    $res_template = M('wish_template')->where(array('template_id'=>$template_id))->find();
    //商品原价
//    $goods_price = $res_wish['goods_price']-C('wish_price');
    $goods_price = $res_wish['goods_price']-$res_pay1['money'];
    //判断人数取最大的
    $assist_num2 = (int)($goods_price / $res_template['assist_money']);
    //确认帮砍人数
    $assist_num = (int)($res_template['assist_num']) > $assist_num2 ? (int)($res_template['assist_num']) : $assist_num2;
    //确认每人帮砍金额
    $assist_price = $res_template['assist_num'] > $assist_num2 ? round($goods_price/$res_template['assist_num'],2) : $res_template['assist_money'];
    //第一阶段人数
    $stage_num1 = (int)($assist_num * $res_template['firstphase_num_percentage']);
    //第二阶段人数
    $stage_num2 = (int)($assist_num * $res_template['secondphase_num_percentage']);
    //第三阶段人数
    $stage_num3 = (int)($assist_num * $res_template['thirdphase_num_percentage']);

    //取现在第几阶段了
    $res_log = M('wish_log')->where(array('wish_id'=>$wish_id))->count();
    if(!$res_log || $res_log < $stage_num1){
        //第一阶段

        //算人数
        //正人数
        $cond_people1 = array(
            'wish_id' => $wish_id,
            'sign' => '+',
            'state' => 1
        );
        $res_plus1 = M('wish_log')->where($cond_people1)->count();
        //负人数
        $cond_people2 = array(
            'wish_id' => $wish_id,
            'sign' => '-',
            'state' => 1
        );
        $res_plus2 = M('wish_log')->where($cond_people2)->count();
        if($res_plus1 >= $stage_num1/2){
            $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],0)*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 1;
        }else if($res_plus2 >= $stage_num1/2){
            $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 1;
        }else{
            $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 1;
        }

    }else if($res_log >= $stage_num1 && $res_log < $stage_num1 + $stage_num2){
        //第二阶段

        //算人数
        //正人数
        $cond_people1 = array(
            'wish_id' => $wish_id,
            'sign' => '+',
            'state' => 2
        );
        $res_plus1 = M('wish_log')->where($cond_people1)->count();
        //负人数
        $cond_people2 = array(
            'wish_id' => $wish_id,
            'sign' => '-',
            'state' => 2
        );
        $res_plus2 = M('wish_log')->where($cond_people2)->count();
        if($res_plus1 > $stage_num2/2){
            $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],0)*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 2;
        }else if($res_plus2 >= $stage_num2/2){
            $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 2;
        }else{
            $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 2;
        }
    }else if($res_log >= $stage_num1 + $stage_num2){
        //第三阶段
        //出去一二阶段剩余钱数
        $cond['wish_id'] = $wish_id;
        $cond['stage'] = array('IN','1,2');
        $res_t = M('wish_log')->field('ifnull(sum(money),0) as surplus_money')->where($cond)->find();
        $surplus_money = $res_t['surplus_money'];


        //算人数
        //正人数
        $cond_people1 = array(
            'wish_id' => $wish_id,
            'sign' => '+',
            'state' => 3
        );
        $res_plus1 = M('wish_template')->where($cond_people1)->count();
        //负人数
        $cond_people2 = array(
            'wish_id' => $wish_id,
            'sign' => '-',
            'state' => 3
        );
        $res_plus2 = M('wish_log')->where($cond_people2)->count();
        if($res_plus1 >= $stage_num3/2){
            $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],0)*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 3;
        }else if($res_plus2 >= $stage_num3/2){
            $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 3;
        }else{
            $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
            $sm2 = (float)sprintf("%.2f",randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
            $money = $sm1 + $sm2;
            $sign = $sm2 >= 0 ? '+' : '-';
            $stage = 3;
        }

        //算总钱数
        $rs_log = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where(array('wish_id'=>$wish_id))->find();
        //算总人数
        $res_log_count = M('wish_log')->where(array('wish_id'=>$wish_id))->count();
        if($rs_log['smoney'] + $money >= $goods_price){
            if($rs_log['smoney'] >= $goods_price){
                var_dump('111');exit;
                return false;
            }
            if($res_log_count + 1 >= $assist_num - $res_template['plus_minus'] && $res_log_count + 1 <= $assist_num + $res_template['plus_minus']){
                //正好在区间直接成交
                $money = $goods_price - $rs_log['smoney'];
                $fsh = true;
            }else if($res_log_count + 1 < $assist_num - $res_template['plus_minus']){
                //不够人数 把钱下降
                $money = round($money/($assist_num-$res_log_count),2);
            }else if($res_log_count + 1 > $assist_num - $res_template['plus_minus']){
                //人数大于区间直接成交
                $money = $goods_price-$rs_log['smoney'];
                $fsh = true;
            }else{
                var_dump('222');exit;
                //其他条件不动
            }
        }else{
            var_dump('333');exit;
            //其他条件不动
//            return false;
        }


    }

    return array(
        'money' => $money,
        'sign' => $sign,
        'stage' => $stage,
        'fsh' => $fsh ? $fsh = true : false
    );


}
//随机数
function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

//创建文件夹
function mkdirs($dir)
{
    if(!is_dir($dir))
    {
        if(!mkdirs(dirname($dir))){
            return false;
        }
        if(!mkdir($dir,0777)){
            return false;
        }
        chmod($dir, 0777);
    }
    return true;
}

function accountAndCommission($order_id){
    !$order_id ? $order_id = $_POST['order_id'] : $order_id;
    $res_order = M('order')->where(array('order_id'=>$order_id))->find();
    M('order')->startTrans();
    if(!$res_order){
        M('order')->rollback();
        return false;
    }
    $res_order_goods = M('order_goods')->where(array('order_id'=>$order_id))->find();
    M('order')->startTrans();
    if(!$res_order_goods){
        M('order')->rollback();
        return false;
    }
    $res_member = M('member')->where(array('user_id'=>$res_order['buyer_id']))->find();
    if(!$res_member){
        M('order')->rollback();
        return false;
    }
    //推荐人
    if($res_member['second_class']){
        $res_refer = M('member')->where(array('user_id'=>$res_member['second_class']))->find();
        if(!$res_refer){
            M('order')->rollback();
            return false;
        }
        //验证推荐人
        if($res_refer['is_promoters'] == 1 && $res_member['first_class'] == 2 && $res_member['second_class'] == $res_refer['user_id'] && $res_member['third_class'] == $res_refer['user_id']){
            //取比例
            $res_config = M('mall_config')->where(array('code'=>'promotion_proportion'))->find();
            if(!$res_config['value']){
                M('order')->rollback();
                return false;
            }
            $commssion_amount = (float)$res_order_goods['price_amount']*(float)$res_config['value'];

            //存流水
            $res_member_save = M('member')->where(array('user_id'=>$res_refer['user_id']))->save(array('commission'=>(float)$res_refer['commission']+$commssion_amount));
            if(!$res_member_save){
                M('order')->rollback();
                return false;
            }
//                $res_order_save = M('order')->where(array('order_id'=>$res_order['order_id']))->save(array('is_change'=>1));
//                if(!$res_order_save){
//                    M('order')->rollback();
//                    return false;
//                }
            //存订单明细
            $data_commission = array(
                'user_id' => $res_refer['user_id'],
                'sign' => '+',
                'commission_money' => $commssion_amount,
                'finish_time' => time(),
                'remark' => '佣金结算'
            );
            $res_commission = M('commission')->add($data_commission);
            if (!$res_commission){
                M('order')->rollback();
                return false;
            }
            //存佣金明细
            $data_commission_log = array(
                'user_id' => $res_refer['user_id'],
                'fans_id' => $res_member['user_id'],
                'sign' => '+',
                'order_id' => $res_order['order_id'],
                'order_money' => $res_order_goods['price_amount'],
                'commission_money' => $commssion_amount,
                'finish_time' => time()
            );
            $res_commission_log = M('commission_log')->add($data_commission_log);
            if (!$res_commission_log){
                M('order')->rollback();
                return false;
            }

            //存入账detail
            $res_goods = M('goods')->where(array('good_id'=>$res_order_goods['good_id']))->find();
            $res_spec = M('goods_spec')->where(array('spec_id'=>$res_order_goods['spec_id']))->find();
            $res_store = M('store')->where(array('store_id'=>$res_refer['user_id']))->find();
            $res_stockstyle = M('')->where(array('storestock_id'=>$res_spec['spec_3value']))->find();
            if(!$res_goods || !$res_spec || !$res_store){
                M('order')->rollback();
                return false;
            }
            $data_commission_detail = array(
                'order_id' => $res_order['order_id'],
                'user_id' => $res_refer['user_id'],
                'order_sn' => $res_order['order_sn'],
                'order_pay_time' => $res_order['pay_time'],
//                    'order_finish_time' => $res_order['finished_time'],
                'goods_id' => $res_goods['goods_id'],
                'spec_id' => $res_spec['spec_id'],
                'goods_name' => $res_goods['goods_name'],
                'sku' => $res_spec['sku'],
                'price' => $res_order_goods['price_amount'],
                'num' => 1,
                'price_amount' => $res_order_goods['price_amount'],
                'sign' => '+',
                'commission_proportion' => $res_config['value'],
                'commission' => (float)$res_order_goods['price_amount'] * (float)$res_config['value'],
                'stock_style' => $res_spec['spec_3value'] == 25 ? '香港直邮' : '境内仓',
                'user_name' => $res_refer['phone_mob'],
                'serial_number' => $res_store['serial_number']

            );
            $res_commission_detail = M('commission_detail')->add($data_commission_detail);
            if (!$res_commission_detail){
                M('order')->rollback();
                return false;
            }
        }
    }


    M('order')->commit();
}

function mergeImage($oriImg, $addImg, $newImg, $addPos = 0)
{

    $oriInfo = @getimagesize($oriImg);
    $oriImg_w  = $oriInfo[0];
    $oriImg_h  = $oriInfo[1];

    switch ($oriInfo[2])
    {
        case 1:
            $oriim =imagecreatefromgif($oriImg);
            break;
        case 2:
            $oriim =imagecreatefromjpeg($oriImg);
            break;
        case 3:
            $oriim =imagecreatefrompng($oriImg);
            break;
        default:
            die("不支持的图片文件类型");
            exit;
    }

    /*合成后图片路径为空就覆盖原图*/
    if (empty($newImg)){
        $newImg = $oriImg;
    }

    if(!file_exists($addImg) || empty($addImg))
    {
        die("待添加图片不能为空");
    }

    $addImgInfo = @getimagesize($addImg);
    $addImg_w  = $addImgInfo[0];
    $addImg_h  = $addImgInfo[1];

    if($oriImg_w < $addImg_w || $oriImg_h < $addImg_h)
    {
        die("原图片尺寸不能小于待添加图片");
    }

    switch ($addImgInfo[2])
    {
        case 1:
            $addim =imagecreatefromgif($addImg);
            break;
        case 2:
            $addim =imagecreatefromjpeg($addImg);
            break;
        case 3:
            $addim =imagecreatefrompng($addImg);
            break;
        default:
            die("不支持的图片文件类型");
            exit;
    }

//    switch($addPos)
//    {
//        case 1:
//            $x = +5;
//            $y = +5;
//            break;
//        case 2:
//            $x = ($oriImg_w - $addImg_w) / 2;
//            $y = +5;
//            break;
//        case 3:
//            $x = $oriImg_w - $addImg_w - 5;
//            $y = +15;
//            break;
//        case 4:
//            $x = +5;
//            $y = ($oriImg_h - $addImg_h) / 2;
//            break;
//        case 5:
//            $x = ($oriImg_w - $addImg_w) / 2;
//            $y = ($oriImg_h - $addImg_h) / 2;
//            break;
//        case 6:
//            $x = $oriImg_w - $addImg_w - 5;
//            $y = ($oriImg_h - $addImg_h) / 2;
//            break;
//        case 7:
//            $x = +5;
//            $y = $oriImg_h - $addImg_h - 5;
//            break;
//        case 8:
//            $x = ($oriImg_w - $addImg_w) / 2;
//            $y = $oriImg_h - $addImg_h - 5;
//            break;
//        case 9:
//            $x = $oriImg_w - $addImg_w - 5;
//            $y = $oriImg_h - $addImg_h -5;
//            break;
//        default:
//            die("此位置不支持");
//            exit;
//    }


    $x = 229 + 5;
    $y = 994 - 5;

    $dst_img = @imagecreatetruecolor($oriImg_w, $oriImg_h);
    imagecopy($dst_img, $oriim, 0, 0, 0, 0, $oriImg_w, $oriImg_h);
    imagecopy($dst_img, $addim, $x, $y, 0, 0, $addImg_w, $addImg_h);
    imagedestroy($addim);

    switch ($oriInfo[2])
    {
        case 1:
            imagegif($dst_img, $newImg);
            break;
        case 2:
            imagejpeg($dst_img, $newImg);
            break;
        case 3:
            imagepng($dst_img, $newImg);
            break;
        default:
            die("不支持的图片文件类型");
            exit;
    }

    imagedestroy($dst_img);
    imagedestroy($oriim);
}
/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 * @return bool
 */
function check_mobile($mobile){
    if(preg_match('/^1[0123456789]\d{9}$/',$mobile))
        return true;
    return false;
}
